package com.yuanye.yeecho.base;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentTransaction;

import com.yuanye.yeecho.R;
import com.yuanye.yeecho.adapter.TaskListAdapter;

import java.util.ArrayList;
import java.util.List;

public abstract class CommonActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    protected String TAG = CommonActivity.class.getSimpleName();

    protected String mTitle;
    protected ListView listView;
    protected TextView tvTaskName, tvStatus;
    protected RelativeLayout statusBar;
    protected Button btnTest;
    protected List<BaseFragment> fragments;
    protected BaseFragment currentFragment;
    protected TaskListAdapter adapter;
    protected boolean isAutoRun = false;
    protected boolean isFirstBoot = true;
    protected Handler handler;
    protected boolean isAllPass = false;
    protected boolean isLocked = false;
    protected ProgressDialog progressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (isFirstBoot && isAutoRun){
            isFirstBoot = false;
            //启动测试
            startAutoTest();
        }
    }



    private void init() {
        mTitle = getTitle().toString();
        handler = new UiHandler();
        progressDialog = new ProgressDialog(this);
        fragments = new ArrayList<>();
        //添加测试fragment
        addFragments();
        //预加载fragment
        loadFragments();
        //初始化界面
        initView();
    }

    /**
     * 开启自动测试
     */
    protected void enableAutoTest(){
        isAutoRun = true;
    }

    /**
     * 允许添加自定义测试fragment
     * 可以使用protected方法addOneFragment进行添加
     */
    protected abstract void addFragments();

    protected void addOneFragment(BaseFragment fragment){
        fragments.add(fragment);
        fragment.setHandler(handler);
    }

    /**
     * 加载所有fragment到FragmentTransaction，并隐藏它们
     */
    private void loadFragments() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        for (int i=0; i<fragments.size(); i++){
            BaseFragment fragment = fragments.get(i);
            fragment.setTaskId(i);
            transaction.add(R.id.frameLayout, fragment, fragment.getTaskName());
            transaction.hide(fragment);
        }
        transaction.commitNow();
    }

    private void initView() {
        setContentView(R.layout.activity_common);
        listView = findViewById(R.id.listView);
        listView.setOnItemClickListener(this);
        adapter = new TaskListAdapter(this, fragments);
        listView.setAdapter(adapter);
        tvTaskName = findViewById(R.id.tvTitle);
        statusBar = findViewById(R.id.status_bar);
        tvStatus = findViewById(R.id.tvStatus);
        btnTest = findViewById(R.id.btnTest2);
        btnTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentFragment != null)
                    currentFragment.execTask();
            }
        });
    }

    /**
     * 处理各测试fragment发送过来的消息 - 更新adapter状态
     * PASS - 判断是否需要提交报告
     * FAIL - 判断是否需要提交报告，并退出自动测试模式
     * NEXT - 跳转下一项测试
     * PASS_AND_NEXT - 判断是否需要提交报告，若不需要，则继续跳转下一下测试
     */
    class UiHandler extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Log.d(TAG, "handleMessage: "+msg.obj);
            adapter.notifyDataSetChanged();
            int id = 0;
            switch (msg.what){
                case Yeecho.PASS:
                    id = (int) msg.obj;
                    Log.d(TAG, "handleMessage: "+fragments.get(id).getTaskName()+" - 测试成功");
                    if (isNeedToReport()){
                        uploadReport();
                    }
                    break;
                case Yeecho.FAIL:
                    id = (int) msg.obj;
                    Log.d(TAG, "handleMessage: "+fragments.get(id).getTaskName()+" - 测试失败");
                    if (isNeedToReport()){
                        uploadReport();
                    }
//                    quitAutoModel();
                    break;
                case Yeecho.NEXT:
                    id = (int) msg.obj;
                    Log.d(TAG, "handleMessage: "+fragments.get(id).getTaskName()+" - 进入后台");
                    //若处于自动模式并且非最后一项，则跳转下一项测试
                    int index = id;
                    if (isAutoRun && ++index < fragments.size()){
                        showFragment(index);
                    }
                    break;
                case Yeecho.PASS_AND_NEXT:
                    id = (int) msg.obj;
                    Log.d(TAG, "handleMessage: "+fragments.get(id).getTaskName()+" - 测试成功并进入下一项");
                    if (isNeedToReport()){
                        uploadReport();
                    }else {
                        int index2 = id;
                        if (isAutoRun && ++index2 < fragments.size()){
                            showFragment(index2);
                        }
                    }
                    break;
                case Yeecho.LOCK:
                    isLocked = true;
                    tvStatus.setText("测试中..");
                    btnTest.setEnabled(false);
                    break;
                case Yeecho.UNLOCK:
                    isLocked = false;
                    tvStatus.setText("");
                    btnTest.setEnabled(true);
                    break;
                case Yeecho.SHOW_TEST_BUTTON:
                    showButton(true);
                    break;
                case Yeecho.HIDE_TEST_BUTTON:
                    showButton(false);
                    break;
                case Yeecho.UPDATE_STATUS:
                    String content = msg.obj.toString();
                    updateStatus(content);
                    break;

            }
        }
    }

    private void quitAutoModel(){
        isAutoRun = false;
        setTitle(mTitle+"（手动）");
    }

    protected void uploadReport() {
        toast("模拟上传报告..");
    }

    protected void updateMesInfo(){
        toast("模拟MES过站..");
    }

    /**
     * 判断当前状态测试是否需要提交报告
     * @return
     */
    private boolean isNeedToReport(){
        //未处于自动模式，不提交
        if (!isAutoRun) return false;
        //有测试项仍处于测试中，不提交
        for (BaseFragment fragment: fragments){
            if (fragment.getState() == fragment.TESTING){
                return false;
            }
        }
        //没有测试中的项，但有FAIL项，提交
        for (BaseFragment fragment: fragments){
            if (fragment.getState() == fragment.FAIL){
                quitAutoModel();
                return true;
            }
        }
        //没有FAIL项，但是没有全PASS，不提交
        for (BaseFragment fragment: fragments){
            if (fragment.getState() != fragment.PASS){
                return false;
            }
        }
        quitAutoModel();
        isAllPass = true;
        return true;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (isLocked){
            tvStatus.setText("测试中，无法切换页面");
            return;
        }
        Log.d(TAG, "onItemClick: "+i);
        if (isAutoRun){
            quitAutoModel();
        }
        showFragment(i);
    }


    /**
     * 开启自动测试
     */
    private void startAutoTest() {
        isAutoRun = true;
        setTitle(mTitle+"（自动模式）");
        showFragment(0);
    }

    /**
     * 隐藏当前fragment, 显示指定id的fragment
     * 若处于自动测试模式，默认执行指定id的fragment的方法execTask
     * @param i = fragment id
     */
    private void showFragment(int i) {
        if (i>=fragments.size()){
            Log.d(TAG, "showFragment: "+"id超出了fragments数组边界");
            return;
        }
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        BaseFragment newFragment = fragments.get(i);
        if (newFragment != null){
            if (currentFragment != null){
                transaction.hide(currentFragment);
            }
            transaction.show(newFragment);
            currentFragment = newFragment;
            transaction.commit();
        }
        //设置测试项标题
        tvTaskName.setText(currentFragment.getTaskName());
        //自启动
        if (isAutoRun){
            currentFragment.execTask();
        }
    }

    protected void showButton(boolean enable){
        btnTest.setVisibility(enable ? View.VISIBLE : View.GONE);
    }

    protected void updateStatus(String content){
        updateStatus(content, 3000);
    }

    protected void updateStatus(String content, int duration){
        handler.removeCallbacks(clearStatusRunnable);
        tvStatus.setText(content);
        handler.postDelayed(clearStatusRunnable, duration);
    }

    protected Runnable clearStatusRunnable = new Runnable() {
        @Override
        public void run() {
            tvStatus.setText("");
        }
    };
}
